﻿using System;
using System.Collections.Generic;
using System.Text;
using com.tiyma.model;
using com.tiyma.common;
using Lucene.Net.Documents;
using Lucene.Net.Search;
using Lucene.Net.QueryParsers;
using System.Web;
using System.IO;

namespace com.tiyma.components
{
    public partial class BookManager
    {
        /// <summary>
        /// 获取用户书架图书
        /// </summary>
        /// <param name="i_user_id"></param>
        /// <returns></returns>
        public List<BookInfo> GetUserBook(long i_user_id)
        {

            try
            {
                List<string> t_book_list = m_boo_dao.GetUserBook(i_user_id);

                if (t_book_list == null || t_book_list.Count <= 0)
                    return null;

                return GetBookListByBookNames(t_book_list);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取用户书架图书失败" + ex.ToString());
               
                return null;
            }
        }

        /// <summary>
        /// 获取最近阅读小说
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetCurReadBook()
        {
            string t_cur_read_book = CookieManager.GetBookReadCookie();


            if (!string.IsNullOrEmpty(t_cur_read_book))
            {
                string[] t_book_arr = t_cur_read_book.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);

                try
                {

                    List<string> t_list = new List<string>();
                    Dictionary<string, string> t_dic = new Dictionary<string, string>();

                    foreach (string t_book_name in t_book_arr)
                    {
                        if (!t_dic.ContainsKey(HttpUtility.UrlDecode(t_book_name)))
                        {
                            t_dic.Add(HttpUtility.UrlDecode(t_book_name), HttpUtility.UrlDecode(t_book_name));
                            t_list.Add(HttpUtility.UrlDecode(t_book_name));
                        }
                       
                    }

                    return GetBookListByBookNames(t_list);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("获取你可能喜欢看的小说失败" + ex.ToString());
                   
                    return null;
                }
            }

            return null;
        }


        #region 根据图书名称获取图书信息
        /// <summary>
        /// 根据图书名称列表获取小说信息
        /// </summary>
        /// <param name="i_list"></param>
        /// <returns></returns>
        public List<BookInfo> GetBookListByBookNames(List<string> i_list)
        {
            if (i_list == null)
                return null;


            if (AppConfig.WebService)
            {
                IRemoting.IRemoting t_remoting = new com.tiyma.components.IRemoting.IRemoting();
                t_remoting.Url = AppConfig.WebServiceUrl;
                com.tiyma.components.IRemoting.BookInfo[] t_book_arr = t_remoting.GetBookListByBookNames(i_list.ToArray());
            }

            IndexSearcher t_seo = null;
            try
            {

                List<BookInfo> t_list = null;

                string t_index_path = AppConfig.BookIndexPath;

                if (string.IsNullOrEmpty(t_index_path) || !Directory.Exists(t_index_path))
                {
                    LogHelper.Info("搜索小说的目录不存在!");
                    return null;
                }

                BooleanQuery t_bq = new BooleanQuery();
                foreach (string t_book_name in i_list)
                {
                    QueryParser t_book_name_query = new QueryParser("BOOKNAME", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                    Query t_query = t_book_name_query.Parse(t_book_name);
                    t_bq.Add(t_query, BooleanClause.Occur.SHOULD);
                }

                t_seo = new IndexSearcher(AppConfig.BookIndexPath);

                Hits t_hits = t_seo.Search(t_bq);

                if (t_hits.Length() == 0)
                {

                    LogHelper.Info("lucune获取最近读者书架图书失败");
                }

                t_list = new List<BookInfo>();
                BookInfo t_book = null;
                int t_site_id = 0;

                Dictionary<string, string> t_dic = new Dictionary<string, string>();
                for (int index = 0; index < t_hits.Length(); index++)
                {

                    Document t_doc = t_hits.Doc(index);
                    t_book = new BookInfo();
                    t_book.BookId = t_doc.Get("BOOKID");
                    t_book.BookName = t_doc.Get("BOOKNAME");
                    t_book.AuthorName = t_doc.Get("AUTHORNAME");
                    t_book.BookCategory = t_doc.Get("BOOKCATEGORY");
                    t_book.BookSubCategory = t_doc.Get("BOOKSUBCATEGORYNAME");
                    t_book.Description = t_doc.Get("DESCRIPTION");
                    t_book.LastUpdateChapterId = t_doc.Get("LASTUPDATECHAPTERID");
                    t_book.LastUpdateChapterName = t_doc.Get("LASTUPDATECHAPTERNAME");
                    t_book.LastUpdateTime = DateTime.Parse(t_doc.Get("LASTUPDATETIME"));

                    if (!int.TryParse(t_doc.Get("SITEID"), out t_site_id))
                        t_site_id = 1;
                    t_book.SiteId = t_site_id;
                    t_book.SiteName = t_doc.Get("SITENAME");

                    if (!t_dic.ContainsKey(t_book.BookName))
                    {
                        t_dic.Add(t_book.BookName, t_book.BookName);
                        t_list.Add(t_book);
                    }
                }
                t_seo.Close();
                return t_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取用户书架图书失败" + ex.ToString());
                if (t_seo != null)
                    t_seo.Close();
                return null;
            }
        }
        #endregion

        /// <summary>
        /// 获取推荐的你可能喜欢看得小说
        /// </summary>
        /// <param name="i_book_name"></param>
        /// <param name="i_category_name"></param>
        /// <param name="i_author_name"></param>
        /// <returns></returns>
        public List<BookInfo> GetRecommendBook(HttpRequest i_request, string i_book_name, string i_category_name, string i_author_name)
        {
            List<BookInfo> t_list = null;
            IndexSearcher t_seo = null;
            try
            {
                string t_index_path = AppConfig.BookIndexPath;

                if (string.IsNullOrEmpty(t_index_path) || !Directory.Exists(t_index_path))
                {
                    LogHelper.Info("搜索小说的目录不存在!" + t_index_path);
                    return null;
                }

                BooleanQuery t_bq = new BooleanQuery();

                QueryParser t_book_name_query = new QueryParser("BOOKNAME", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                Query t_query_1 = t_book_name_query.Parse(i_book_name);
                t_bq.Add(t_query_1, BooleanClause.Occur.MUST_NOT);

                if (!string.IsNullOrEmpty(i_author_name))
                {
                    QueryParser t_autuor_name_query = new QueryParser("AUTHORNAME", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                    Query t_query_2 = t_autuor_name_query.Parse(i_author_name);
                    t_bq.Add(t_query_2, BooleanClause.Occur.SHOULD);
                }

                if (!string.IsNullOrEmpty(i_category_name))
                {
                    QueryParser t_category_query = new QueryParser("BOOKCATEGORY", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                    Query t_query_3 = t_category_query.Parse(i_category_name);
                    t_bq.Add(t_query_3, BooleanClause.Occur.SHOULD);
                }

                t_seo = new IndexSearcher(AppConfig.BookIndexPath);

                Hits t_hits = t_seo.Search(t_bq);

                if (t_hits.Length() == 0)
                {
                   // LogHelper.Info(string.Format("获取你喜欢小说从seo路径：{0}搜索关键字：{1}得到0条记录,url={2},UrlReferrer={3}", AppConfig.BookIndexPath, i_book_name, i_request.Url, i_request.UrlReferrer==null?"":i_request.UrlReferrer.ToString()));
                }

                t_list = new List<BookInfo>();
                BookInfo t_book = null;
                int t_site_id = 0;

                Dictionary<string, string> t_dic = new Dictionary<string, string>();
                for (int index = 0; index < t_hits.Length(); index++)
                {

                    Document t_doc = t_hits.Doc(index);
                    t_book = new BookInfo();
                    t_book.BookId = t_doc.Get("BOOKID");
                    t_book.BookName = t_doc.Get("BOOKNAME");
                    t_book.AuthorName = t_doc.Get("AUTHORNAME");
                    t_book.BookCategory = t_doc.Get("BOOKCATEGORY");
                    t_book.LastUpdateChapterName = t_doc.Get("LASTUPDATECHAPTERNAME");

                    if (!int.TryParse(t_doc.Get("SITEID"), out t_site_id))
                        t_site_id = 1;
                    t_book.SiteId = t_site_id;
                    t_book.SiteName = t_doc.Get("SITENAME");

                    if (!t_dic.ContainsKey(t_book.BookName))
                    {
                        t_dic.Add(t_book.BookName, t_book.BookName);
                        t_list.Add(t_book);
                    }

                    if (t_dic.Count == 10)
                        break;
                }
                t_seo.Close();
                return t_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取你可能喜欢看的小说失败" + ex.ToString());
                if (t_seo != null)
                    t_seo.Close();
                return null;
            }
        }


        /// <summary>
        /// 获取分类的点击排行榜
        /// </summary>
        /// <param name="i_category_name"></param>
        /// <returns></returns>
        public List<BookInfo> GetRecomendBookByCategory(string i_category_name, int i_count, HttpRequest i_request)
        {

            string t_url = i_request.Url.ToString();
            //缓存48个小时
            string t_cache_key = t_url.Substring(t_url.LastIndexOf("/"));

            if (string.IsNullOrEmpty(t_cache_key))
                t_cache_key = t_url;
     

            List<BookInfo> t_list = null;

            if (HttpContext.Current.Cache[t_cache_key] != null)
            {
                t_list = HttpContext.Current.Cache[t_cache_key] as List<BookInfo>;

                if (t_list != null && t_list.Count > 0)
                    return t_list;
            }

            IndexSearcher t_seo = null;

            try
            {
                string t_index_path = AppConfig.BookIndexPath;

                if (string.IsNullOrEmpty(t_index_path) || !Directory.Exists(t_index_path))
                {
                    LogHelper.Info("搜索小说的目录不存在!" + t_index_path);
                    return null;
                }

                BooleanQuery t_bq = new BooleanQuery();
               
                QueryParser t_category_query = new QueryParser("BOOKCATEGORY", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                Query t_query = t_category_query.Parse(i_category_name);
                t_bq.Add(t_query, BooleanClause.Occur.MUST);


                Sort t_sort = new Sort();
                SortField t_sort_field = new SortField("CLICKCOUNT", SortField.INT, true);//按照点击数字段排序，true表示降序
                t_sort.SetSort(t_sort_field);


                t_seo = new IndexSearcher(AppConfig.BookIndexPath);

                Hits t_hits = t_seo.Search(t_bq, t_sort);

                int t_total_count = t_hits.Length();

                t_list = new List<BookInfo>();

                int t_site_id = 1;

                BookInfo t_book = null;

                for (int index = 0; index < i_count; index++)
                {
                    if (index >= t_total_count)
                        break;
                    Document t_doc = t_hits.Doc(index);

                    t_book = new BookInfo();

                    t_book.BookId = t_doc.Get("BOOKID");
                    t_book.BookName = t_doc.Get("BOOKNAME");

                    t_list.Add(t_book);
                }

                t_seo.Close();

                if (t_list != null && t_list.Count > 0)
                {
                    HttpContext.Current.Cache.Insert(t_cache_key, t_list, null, DateTime.Now.AddHours(48), TimeSpan.Zero);

                }

                return t_list;


            }
            catch (Exception ex)
            {
                LogHelper.Error("获取分类的推介小说失败" + ex.ToString());
                if (t_seo != null)
                    t_seo.Close();
                return null;
            }
        }



        /// <summary>
        /// 搜索小说
        /// </summary>
        /// <param name="i_key_word"></param>
        /// <param name="i_page_index"></param>
        /// <param name="i_page_size"></param>
        /// <param name="o_total_count"></param>
        /// <returns></returns>
        public List<BookInfo> SearchBook(HttpRequest i_request, string i_key_word, Consts.SearchType i_search_type, int i_page_index, int i_page_size, out int o_total_count)
        {
            o_total_count = 0;

            string t_search_field = "";

            if (i_search_type == Consts.SearchType.AuthorName)
                t_search_field = "AUTHORNAME";

            if (i_search_type == Consts.SearchType.BookName)
                t_search_field = "BOOKNAME";

            if (i_search_type == Consts.SearchType.Category)
                t_search_field = "BOOKCATEGORY";

            string t_key_parse = HttpUtility.UrlDecode(HttpUtility.UrlEncode(i_key_word, Encoding.GetEncoding("gb2312")), Encoding.UTF8);

            IndexSearcher t_seo = null;
            try
            {
                string t_index_path = AppConfig.BookIndexPath;

                if (string.IsNullOrEmpty(t_index_path) || !Directory.Exists(t_index_path))
                {
                    LogHelper.Info("搜索小说的目录不存在!" + t_index_path);
                    return null;
                }

                BooleanQuery t_bq = new BooleanQuery();
                if (!string.IsNullOrEmpty(t_search_field))
                {
                    QueryParser t_query_parse = new QueryParser(t_search_field, new Lucene.Net.Analysis.Standard.StandardAnalyzer());

                    Query t_query = t_query_parse.Parse(i_key_word.Trim());

                    Query t_query_2 = t_query_parse.Parse(t_key_parse.Trim());

                    t_bq.Add(t_query, BooleanClause.Occur.SHOULD);
                    t_bq.Add(t_query_2, BooleanClause.Occur.SHOULD);
                }
                else
                {
                    QueryParser t_book_name_query = new QueryParser("BOOKNAME", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                    Query t_query_1 = t_book_name_query.Parse(i_key_word);
                    t_bq.Add(t_query_1, BooleanClause.Occur.SHOULD);

                    QueryParser t_autuor_name_query = new QueryParser("AUTHORNAME", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                    Query t_query_2 = t_autuor_name_query.Parse(i_key_word);
                    t_bq.Add(t_query_2, BooleanClause.Occur.SHOULD);

                    QueryParser t_category_query = new QueryParser("BOOKCATEGORY", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                    Query t_query_3 = t_category_query.Parse(i_key_word);
                    t_bq.Add(t_query_3, BooleanClause.Occur.SHOULD);

                    QueryParser t_sub_category_query = new QueryParser("BOOKSUBCATEGORYNAME", new Lucene.Net.Analysis.Standard.StandardAnalyzer());
                    Query t_query_4 = t_sub_category_query.Parse(i_key_word);
                    t_bq.Add(t_query_3, BooleanClause.Occur.SHOULD);
                }

                Sort t_sort = new Sort();
                SortField t_sort_field = new SortField("BOOKCHAPTERCOUNT", SortField.INT, true);//按照BOOKCHAPTERCOUNT字段排序，true表示降序
                t_sort.SetSort(t_sort_field);


                t_seo = new IndexSearcher(AppConfig.BookIndexPath);

                Hits t_hits = t_seo.Search(t_bq, t_sort);

                o_total_count = t_hits.Length();

                if (o_total_count == 0)
                {
                   // LogHelper.Info(string.Format("从seo路径：{0}搜索关键字：[{1}]-[{4}]得到0条记录,url={2},UrlReferrer={3}", Path.Combine(AppConfig.BookIndexPath, AppConfig.BookIndexPath), i_key_word, i_request.Url, i_request.UrlReferrer == null ? "" : i_request.UrlReferrer.ToString(),t_key_parse));
                }

                List<BookInfo> t_list = new List<BookInfo>();

                int t_site_id = 1;

                BookInfo t_book = null;

                for (int index = (i_page_index - 1) * i_page_size; index < o_total_count && index < (i_page_index * i_page_size + 1); index++)
                {
                    Document t_doc = t_hits.Doc(index);

                    t_book = new BookInfo();

                    t_book.BookId = t_doc.Get("BOOKID");
                    t_book.BookName = t_doc.Get("BOOKNAME");
                    t_book.AuthorName = t_doc.Get("AUTHORNAME");
                    t_book.BookCategory = t_doc.Get("BOOKCATEGORY");
                    t_book.BookSubCategory = t_doc.Get("BOOKSUBCATEGORYNAME");
                    t_book.Description = t_doc.Get("DESCRIPTION");
                    t_book.LastUpdateChapterId = t_doc.Get("LASTUPDATECHAPTERID");
                    t_book.LastUpdateChapterName = t_doc.Get("LASTUPDATECHAPTERNAME");
                    t_book.LastUpdateTime = DateTime.Parse(t_doc.Get("LASTUPDATETIME"));
                    t_book.BookChapterCount = string.IsNullOrEmpty(t_doc.Get("BOOKCHAPTERCOUNT")) ? 0 : Convert.ToInt32(t_doc.Get("BOOKCHAPTERCOUNT"));
                    if (!int.TryParse(t_doc.Get("SITEID"), out t_site_id))
                        t_site_id = 1;
                    t_book.SiteId = t_site_id;
                    t_book.SiteName = t_doc.Get("SITENAME");
                    t_book.IsDownLoad = string.IsNullOrEmpty(t_doc.Get("ISDOWNLOAD")) ? 0 : Convert.ToInt32(t_doc.Get("ISDOWNLOAD"));
                    t_list.Add(t_book);
                }

                t_seo.Close();
                return t_list;


            }
            catch (Exception ex)
            {
                LogHelper.Error("搜索小说失败" + ex.ToString());
                if (t_seo != null)
                    t_seo.Close();
                return null;
            }
        }
    }
}
